package com.cyh.pangu.ds;

/**
 * 数组扩容Demo
 */
public class ArrayResizeDemo {

    /**
     * 数组
     */
    private int[] arrsInt;

    /**
     * 实际大小
     */
    private int size;

    public ArrayResizeDemo(int capacity) {
        this.arrsInt = new int[capacity];
        this.size = 0;
    }


    public void insert(int index, int value) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("下标越界");
        }

        if (index >= arrsInt.length) {
            resize();
        }
        for (int i = size; i > index; i--) {
            arrsInt[i] = arrsInt[i - 1];
        }
        arrsInt[index] = value;
        size++;
    }

    public void resize() {
        int[] newArrInt = new int[arrsInt.length * 2];
        System.arraycopy(arrsInt, 0, newArrInt, 0, arrsInt.length);
        arrsInt = newArrInt;
    }

    public void printArr() {
        System.out.println("size:" + size);
        for (int i = 0; i < size; i++) {
            System.out.println((i) + ":" + arrsInt[i]);
        }
    }

    public int delete(int index) {
        if (index < 0 || index > arrsInt.length - 1) {
            throw new IndexOutOfBoundsException("超出数组下标");
        }
        int deleteNum = arrsInt[index];
        for (int i = index; i < size - 1; i++) {
            arrsInt[i] = arrsInt[i+1];
        }
        size--;
        return deleteNum;
    }

    public static void main(String[] args) {
        ArrayResizeDemo arrayDemo = new ArrayResizeDemo(3);
        arrayDemo.insert(0, 10);
        arrayDemo.insert(1, 1);
        arrayDemo.insert(2, 2);
        arrayDemo.insert(3, 3);
        arrayDemo.insert(4, 4);
        arrayDemo.insert(5, 5);

        arrayDemo.printArr();
        arrayDemo.delete(5);
        arrayDemo.printArr();
    }
}
